package com.cht.commonUtil.jenkins;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.jenkins.JenkinsJob.Action;
import com.cht.commonUtil.enums.MailType;
import com.cht.commonUtil.enums.RecipientType;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class PostActionFail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


		
		/*
		 * 1.	寫入log
		 * 
		 * */
		
		
		String sql = "INSERT INTO buildLog (modId,jobSN,rootJobId,rootJobSN,bDT,eDT,buildResult,chkInId) VALUES (?,?,?,?,?,?,?,?)";
		String modId = request.getParameter("modId");
		String subsysId = request.getParameter("subsysId");
		String rootJobId = "";
		int rootJobSN = 0;
		int chkInId = Integer.parseInt( request.getParameter("chkInId") );
		boolean isOL = Boolean.parseBoolean( request.getParameter("isOL") );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs= null;
		
		File errorMsgFile = null;
		
		String json = "";
		try {
			//取得最後執行的job號
			json = Widgets.readUrl( Widgets.getJenkinsUrl(modId, 0, "json") );
			int jobSN = new Gson().fromJson(json, JenkinsJobFull.class ).getLastBuild().getNumber();	//取得目前的jobSN
			
			json = Widgets.readUrl( Widgets.getJenkinsUrl(modId, jobSN, "json") );
			JenkinsJob jobStatus = new Gson().fromJson(json, JenkinsJob.class );
			for( Action act : jobStatus.getActions() ) {
				if( act.getCauses() != null && act.getCauses().size() != 0 ) {
					String shortDescription = act.getCauses().get(0).getShortDescription();
					rootJobId = shortDescription.substring("Started by build flow ".length(), shortDescription.lastIndexOf("#") );
					rootJobSN = Integer.parseInt( shortDescription.substring( shortDescription.lastIndexOf("#")+1,shortDescription.length()) );
				}
			}
			
			String result = jobStatus.getResult();	//取得這個job的執行結果
			
			Timestamp cDT = Widgets.cDT();			//目前的Timestamp
			
			//加入持續時間，以得結束時間
			Calendar cal = Calendar.getInstance();	
	        cal.setTimeInMillis( cDT.getTime() );
	        cal.add( Calendar.MILLISECOND, jobStatus.getDuration() );
	        Timestamp eDT = new Timestamp( cal.getTime().getTime() );
			
			conn = Widgets.getConn();
			
			//寫入執行記錄
			ps = conn.prepareStatement(sql, new String[] { "buildLogSN" });
			ps.setString(1, modId);
			ps.setInt(2, jobSN);
			ps.setString(3, rootJobId);
			ps.setInt(4, rootJobSN);
			ps.setTimestamp(5, cDT );
			ps.setTimestamp(6, eDT );
			ps.setString(7, result);
			ps.setInt(8, chkInId);
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			rs.next();
			final int BUILD_LOG_SN =rs.getInt(1);
			if ( ps !=null ) {ps.close();}
			if ( rs !=null ) { rs.close(); }
			
			String errorMsgOnJenkins = Widgets.readUrl( Widgets.getJenkinsConsoleMsg(modId, jobSN) );
			errorMsgFile = Widgets.string2File(errorMsgOnJenkins,(isOL?"OL_":"MR_")+modId+"-"+jobSN+"-errMsg.txt");
			
			sql = "INSERT INTO errorbuildlog (errorBuildLogSN,msg) VALUES (null,?)";
			ps = conn.prepareStatement(sql, new String[] {"errorBuildLogSN"});
			ps.setString(1, errorMsgOnJenkins);
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			rs.next();
			final int ERROR_BUILD_LOG =rs.getInt(1);

			sql = "UPDATE buildlog SET errorBuildLogSN=? WHERE buildLogSN=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, ERROR_BUILD_LOG);
			ps.setInt(2, BUILD_LOG_SN);
			ps.executeUpdate();
			if ( ps !=null ) {ps.close();}
			if ( rs !=null ) { rs.close(); }
			
			sql = "SELECT subsysDesc FROM subsyses WHERE subsysId=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			rs = ps.executeQuery();
			rs.next();
			String subsysDesc = rs.getString("subsysDesc");
			
			//開始寄通知信
			List<String[]> tos = Widgets.getRecipient(MailType.BUILD_FAIL, RecipientType.TO, subsysId);
			List<String[]> ccs = Widgets.getRecipient(MailType.BUILD_FAIL, RecipientType.CC, subsysId);
			List<String[]> bccs = Widgets.getRecipient(MailType.BUILD_FAIL, RecipientType.BCC, subsysId);
			String subject = subsysDesc+"-封裝原始碼失敗-"+chkInId;
			
			Widgets.sendMailMain(tos,ccs,bccs,subject,"",errorMsgFile);
			
		} catch( Exception e ) {
			e.printStackTrace();
		} finally {
			try {
				if( errorMsgFile !=null ) { System.out.println("刪除檔案："+errorMsgFile.delete()); } 
				if ( rs !=null ) { rs.close(); }
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }	
			} catch (Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write(json);
	}
}

